home *** CD-ROM | disk | FTP | other *** search
- Path: thor.tu.hac.com!collins
- From: collins@thor.tu.hac.com (Ron Collins)
- Newsgroups: comp.lang.c
- Subject: Re: union ?
- Date: 18 Jan 1996 14:10:47 GMT
- Organization: Advanced Depot Systems
- Message-ID: <4dlkd7$qj3@hacgate2.hac.com>
- References: <4dkigi$c29@linet02.li.net>
- NNTP-Posting-Host: thor.tu.hac.com
-
- Don Matthews (don@newshost.li.net) wrote:
- : A union consist of many different variables.
- : But at any one time it can only hold one of those variables.
- : Is that correct?
-
- More or less ... a union, in its simplest form, consists of many different
- variables, *all occupying the same storage locations*. For example:
-
- union FOO {
- char var1;
- int var2;
- float var3;
- };
-
- union FOO bar; /* make a variable of the union itself */
-
- I can now assign to any of bar.var1, bar.var2, or bar.var3. A value will
- immediately appear in the other 2 variables. What that value _means_ is
- completely implementation-dependant.
-
- A real-life example (kind of): On an IBM-PC, I want to pack two characters
- (8 bits each) into a single 16-bit integer:
-
- union CPACK_U {
- char cval[2]; /* a total of 16 bits here */
- int ival; /* 16 bits here, too */
- };
-
- union CPACK_U cpack;
-
- cpack.cval[0] = 'A';
- cpack.cval[1] = 'B';
- printf("ival=%4.4x",cpack.ival);
-
- will print "ival=4241" ('A' is hex 41, 'B' is hex 42).
-
- Note that using silly tricks like this make your code completely non-
- portable, and can lead to some of the most frustrating debugging sessions
- of your career. Of course, silly tricks like this are sometimes the
- best way (fastest, cheapest) to get a job done.
-
-
- -- Collins --
-
- -----
- The views expressed here are mine alone.
-
- Ron Collins/Hughes Aircraft Company/M20,P20/Tucson Az 85706
- rcollins@thor.tu.hac.com collins@seagull.rtd.com
- ยก----
-
-
-
-
-